package br.com.future.securityContext;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.apache.http.Header;
import org.apache.http.message.BasicHeader;

import br.com.future.constants.Headers;

/**
 * SecurityContext simple DTO that holds all request/response information. This object will be used by all
 * interceptors/controllers
 * 
 * @author Rafael Castanho Ferreira (mailto: rafa.ferreira@gmail.com)
 * @since 02-2011
 */
public class SecurityContext {

	/**
	 * Represents the list of headers from the original request as well as additional headers added by the interceptors.
	 */
	private List<Header> headers = new ArrayList<Header>();
	private String trackId;
	private String responseContent;
	private int responseStatusCode;

	public SecurityContext() {
		this.trackId = UUID.randomUUID().toString();
		addHeader(Headers.HEADER_TRACK_ID, this.trackId);
	}

	/**
	 * Will add the given header. If the header already exists, then it will be updated with the new value.
	 * 
	 * @param name The name of the header to add or update.
	 * @param value The value of the header.
	 */
	public void addHeader(String name, String value) {
		addOrReplaceHeader(name, value, this.headers);
	}

	public List<Header> getHeaders() {
		return headers;
	}

	public String getTrackId() {
		return trackId;
	}

	public void setResponse(int responseStatusCode, String responseContent) {
		this.setResponseStatusCode(responseStatusCode);
		this.setResponseContent(responseContent);
	}

	public String getResponseContent() {
		return responseContent;
	}

	public void setResponseContent(String responseContent) {
		this.responseContent = responseContent;
	}

	public int getResponseStatusCode() {
		return responseStatusCode;
	}

	public void setResponseStatusCode(int responseStatusCode) {
		this.responseStatusCode = responseStatusCode;
	}

	private void addOrReplaceHeader(String name, String value, List<Header> lstHeaders) {
		Header existingHeader = null;
		for (Header header : lstHeaders) {
			if (header.getName().equalsIgnoreCase(name)) {
				existingHeader = header;
				break;
			}
		}
		if (existingHeader != null) {
			lstHeaders.remove(existingHeader);
		}
		lstHeaders.add(new BasicHeader(name, value));
	}
}
